// @file     Gravic.groovy
// @author   Mac Radigan
// @version  $Id: Gravic.groovy 96 2012-06-10 23:03:11Z mac.radigan $

package org.radigan.ycoa.scan.service

import org.apache.log4j.Logger;
import java.util.concurrent.ExecutionException
import org.radigan.system.configuration.Configuration
import org.apache.commons.io.FileUtils

public class Gravic {
  protected static log = Logger.getLogger(Gravic.class.getName())
  private File executable = new File("c:\\Program Files (x86)\\Gravic\\Remark Office OMR 7\\Roo70.exe")
  private long timeout = 0
  private String response = null

  public Gravic() {
  }

  public Gravic(File executable) {
    this.executable = executable
  }

  public Gravic(File executable, long timeout) {
    this.timeout = timeout
  }

  public File getExecutable() {
     return executable
  }

  public void setResponse(File resourcePath) {
    if(!resourcePath) {
      response = null
    } else {
      response = resourcePath.text
    }
  }

  public void setResponse(String resourcePath) {
    if(!resourcePath) {
      response = null
    } else {
      response = Configuration.getInstance().getResourceManager().getText(resourcePath)
    }
  }

  public void process(File reference, File image, File result) { 
    if(response) {
      result.write(response)
      return
    }
    try {
      if(result.exists()) {
        log.debug "deleting ${result}"
        FileUtils.forceDelete(result)
      }
      def initialSize = 4096
      def outStream = new ByteArrayOutputStream(initialSize)
      def errStream = new ByteArrayOutputStream(initialSize)
      def commandLine = """ "${executable.getAbsolutePath()}" """
      //commandLine += """ /E /T ${reference.getAbsolutePath()} /I ${image.getAbsolutePath()} /Oxml- ${result.getAbsolutePath()} """
      //commandLine += """ /H /Wh /E /T ${reference.getAbsolutePath()} /Ip ${image.getAbsolutePath()} /Oxml ${result.getAbsolutePath()} """
      commandLine += """ /H /Wh /E /T ${reference.getAbsolutePath()} /I ${image.getAbsolutePath()} /Oxml ${result.getAbsolutePath()} """
      log.debug "[executing] ${commandLine}"
      def proc = commandLine.execute()
      proc.consumeProcessOutput(outStream, errStream)
      if(timeout) {
        proc.waitFor()
      } else {
        proc.waitForOrKill(4*60*1000)
      }
      if(proc.exitValue()) throw new ExecutionException("Gravic failed with exit code ${proc.exitValue()}.")
    } catch(e) {
      log.debug "Error running Gravic.", e
      throw new Exception("Error running Gravic.", e)
    }
  } 

}

/* *EOF* */
